import React, {Component} from 'react';
import {
	ActivityIndicator,
	Alert,
	Dimensions,
	FlatList,
	Modal,
	RefreshControl,
	StyleSheet,
	Text,
	TextInput,
	TouchableWithoutFeedback,
	View,
} from 'react-native';
import Toast from '../component/Toast';
import axiosInstance from '../utils/request';

let rows=20;//
let totalPage=0;//总的页数
let itemNo=0;//item的个数

//屏幕信息
var dimensions = require('Dimensions');
//获取屏幕的宽度
const WIN_WIDTH = Dimensions.get('window').width;

export default class CostHisScene extends Component {

    constructor(props){
		super(props);
		this.state = {
			page:1,
			modalVisible: false,//模态场景是否可见
            isLoading: true,
            //网络请求状态
            error: false,
            errorInfo: "",
            dataArray: [],
            showFoot:0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
            isRefreshing:false,//下拉控制
	 	};
	}

	setModalVisible = (visible) => {
    	this.setState({ modalVisible: visible });
    }

	//组件挂载完成后执行的方法
    componentDidMount(){
        //组件挂载后开始下载数据
        this.fetchData();
    }

	fetchData(){
		let custCode=this.state.custCode;
		let custName=this.state.custName;
		let page=this.state.page;
		let url=global.server.url+'/costHis/dataGrid';
		axiosInstance.post(url,
			{
				custCode:custCode,
				custName:custName,
				payWay:'移动APP',
				pageVO:{
					page:page,
					rows:rows
				}
			}).then(res => {
			let sumPayfees=0;
			let datas = [];
			let count=res.records.length;
			totalPage=res.pages;
			datas = datas.concat(res.records);
            let dataBlob = [];//这是创建该数组，目的放存在key值的数据，就不会报黄灯了
            let i = itemNo;
            datas.map(function (item) {
            	dataBlob.push({
                	key: i,
					sno:item.sno,
					custCode:item.custCode,
					custName:item.custName,
					payTime:item.payTime,
                    payfees: item.payfees,
                    payee: item.payee
                })
				sumPayfees+=item.payfees;
                i++;
            });
            itemNo = i;
            let foot = 0;
            if(this.state.page>=totalPage){
                foot = 1;//listView底部显示没有更多数据了
            }
            this.setState({
                dataArray:this.state.dataArray.concat(dataBlob),
                isLoading: false,
                showFoot:foot,
                isRefreshing:false,
				count:count,
				custCode:'',
				custName:'',
				sumPayfees:sumPayfees.toFixed(2),
            });
            datas = null;//重置为空
            dataBlob = null;
		})
		.catch(error => {
        	this.setState({
				error: true,
                errorInfo: error
			});
			Alert.alert("网络异常，请稍后再试！");
        })
	}

	nullify(item){
		let sno=item.sno;
		let payMode=item.payMode;
		let url=global.server.url+'/costHis/nullify';
		if(payMode!=''&&payMode!=null&&payMode==2){
			Toast.show('微信支付暂不支持退费！');
			return;
		}
		axiosInstance.post(url,
			{
				sno:sno,
			}
		)
        .then(res => {
        	if(res.success){
				let dataArray=this.state.dataArray;
				for(let i=0;i<dataArray.length;i++){
					if(sno===dataArray[i].sno){
						dataArray.splice(i,1);
						break;
					}
				}
				this.setState({
					count:dataArray.length,
					dataArray:dataArray
				});
				Toast.show("撤销成功！");
			}else{
				Toast.show("撤销失败！");
			}
        })
        .catch(err => {
        	Toast.show("网络异常，请稍后再试！"+err);
        })
	}

    handleRefresh = () => {
        this.setState({
            page:1,
            isRefreshing:true,//tag,下拉刷新中，加载完全，就设置成flase
            dataArray:[]
        });
        this.fetchData()
    }


	//加载等待页
    renderLoadingView() {
        return (
            <View style={styles.container}>
                <ActivityIndicator
                    animating={true}
                    color='blue'
                    size="large"
                />
            </View>
        );
    }

    _keyExtractor = (item, index) => index;

    //加载失败view
    renderErrorView() {
        return (
            <View style={styles.container}>
                <Text>
                    {this.state.errorInfo}
                </Text>
            </View>
        );
    }

	renderData() {
        return (
			<View style={styles.container}>
				<FlatList
					data = {this.state.dataArray}
					renderItem = {({item}) =>
						<TouchableWithoutFeedback
							onLongPress = { async() => {
								Alert.alert(
									'提示',
									'确定要撤销该收费记录吗?',
										[
											{text: '取消', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
											{text: '确实', onPress: () => this.nullify(item)},
										]
									)
							}}>
							<View style={styles.textMainStyle}>
								<Text style={styles.margin}>用户编号：{item.custCode}</Text>
								<Text style={styles.margin}>用户名称：{item.custName}</Text>
								<Text style={styles.margin}>缴费金额：{item.payfees}</Text>
								<Text style={styles.margin}>收费人员：{item.payee}</Text>
								<Text style={styles.margin}>缴费时间：{item.payTime}</Text>
							</View>
						</TouchableWithoutFeedback>
					}
					ListFooterComponent={this._renderFooter.bind(this)}
					onEndReached={this._onEndReached.bind(this)}
					onEndReachedThreshold={0.1}
					keyExtractor={this._keyExtractor}
					//为刷新设置颜色
					refreshControl={
						<RefreshControl
							refreshing={this.state.isRefreshing}
							onRefresh={this.handleRefresh.bind(this)}//因为涉及到this.state
							colors={['#ff0000', '#00ff00','#0000ff','#3ad564']}
							progressBackgroundColor="#ffffff"
						/>
					}
					ListHeaderComponent={this._renderHeader()}
					ListEmptyComponent={this.emptyComponent}
				/>
			</View>
        );
    }

	searchData(){
		this.setState({
			dataArray:[]
        });
		this.fetchData();
		this.setModalVisible(false);
	}

    render() {
        //第一次加载等待的view
        if (this.state.isLoading && !this.state.error) {
            return this.renderLoadingView();
        } else if (this.state.error) {
            //请求失败view
            return this.renderErrorView();
        }
        //加载数据
        return this.renderData();
    }

	emptyComponent() {
		return (
			<View style={{
				backgroundColor: 'white', flex: 1, height: 500, alignItems: 'center',
				justifyContent: 'center',
			}}>
				<Text>抱歉，没有符合条件的记录，请确认：</Text>
				<Text>1、今日是否有缴费记录。&nbsp;&nbsp;&nbsp;</Text>
				<Text>2、搜索条件输入是否正确。</Text>
			</View>
		)
	}

	//渲染头部
	 _renderHeader = () => {
         return(
            <View>
				{
					this.state.isLoading==true?(
						<Loading/>
					):(null)
				}
				<View style={{
					height:35,
					flexDirection:'row',
					alignItems:'center',
					borderBottomWidth:1,
					borderBottomColor:'#D7D7D7',
					backgroundColor:"#F5FCFF",
					paddingLeft:6
				}}>
					<View style={styles.flex}>
						<Text style={styles.headerText}>总记录数：{this.state.count}</Text>
					</View>
				</View>
				<View style={{alignItems:'center',flex:1}}>
					<Modal
						animationType={this.state.animationType}
						transparent={this.state.transparent}
						visible={this.state.modalVisible}
						onRequestClose={() => {
						  this.setModalVisible(false)
						}}
					 >
						<View style={[styles.modalContainer,{backgroundColor: 'rgba(0, 0, 0, 0.5)'}]}>
							<View style={[styles.innerContainer,{backgroundColor: '#F0F8FF', padding: 20}]}>
								<View style={styles.row}>
									<View >
									  <Text style={styles.tips}>请输入一个或多个条件</Text>
									</View>
									<TextInput
										style={styles.textInput}
										placeholder={'用户名称'}
										onChangeText={(text) => {
											this.custName = text;
											this.setState({custName: text})
										}}
										//输入框下划线
										underlineColorAndroid={'transparent'}/>
									<TextInput
										style={styles.textInput}
										placeholder={'用户编号'}
										onChangeText={(text) => {
											this.custCode = text;
											this.setState({custCode: text})
										}}
										//输入框下划线
										underlineColorAndroid={'transparent'}/>
								</View>
								<View style={styles.settingStyle}>
									<Text
										onPress={this.searchData.bind(this)}
										style={{fontSize:20,marginTop:10}}>
										确定
									</Text>
									<Text
										onPress={this.setModalVisible.bind(this,false) }
										style={{fontSize:20,marginTop:10}}>
										关闭
									</Text>
								</View>
							</View>
						</View>
					</Modal>
      			</View>
            </View>
        )
    }

    _renderFooter(){
        if (this.state.showFoot === 1) {
            return (
                <View style={{height:30,alignItems:'center',justifyContent:'flex-start',}}>
                    <Text style={{color:'#999999',fontSize:14,marginTop:5,marginBottom:5,}}>
                        没有更多数据了
                    </Text>
                </View>
            );
        } else if(this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator />
                    <Text>正在加载更多数据...</Text>
                </View>
            );
        } else if(this.state.showFoot === 0){
            return (
                <View style={styles.footer}>
                    <Text></Text>
                </View>
            );
        }
    }

    _onEndReached(){
        //如果是正在加载中或没有更多数据了，则返回
        if(this.state.showFoot != 0 ){
            return ;
        }
        //如果当前页大于或等于总页数，那就是到最后一页了，返回
        if((this.state.page!=1) && (this.state.page>=totalPage)){
            return;
        } else {
            this.state.page++;
        }
        //底部显示正在加载更多数据
        this.setState({showFoot:2});
        //获取数据，在componentDidMount()已经请求过数据了
    	if (this.state.page>1){
            this.fetchData();
        }
    }
}

var width = WIN_WIDTH/2;
const styles = StyleSheet.create({
	container: {
        flex: 1,
    },
	rowTextContainer:{
        flex:1,
        marginLeft:10,
    },
	headerText:{
		fontSize:16,
		fontWeight:"bold",
		textAlign:"right",
		marginTop:5,
		marginRight:10,
		height:25,
		backgroundColor:"#F5FCFF",
	},
	textMainStyle: {
        flex: 1,
        backgroundColor: 'white',
        padding: 10,
        paddingVertical:10,
        marginLeft: 5,
        marginRight: 5,
        marginVertical: 3,
        borderColor: '#dddddd',
        borderStyle: null,
        borderWidth: 0.5,
        borderRadius: 2,
        shadowColor: 'gray',    // 设置阴影
        shadowOffset: {width:0.5, height: 0.5},
        shadowOpacity: 0.4,   // 透明度
        shadowRadius: 1,
        elevation:2   //   高度，设置Z轴，可以产生立体效果
    },
	modalContainer:{
		flex: 1,
		justifyContent: 'center',
		padding: 40,
    },
    innerContainer: {
		borderRadius: 10,
		alignItems: 'center',
    },
	tips:{
		textAlign: 'center',
		marginBottom: 5,
		fontSize: 20
    },
	flex:{
    	flex:1,
  	},
	textInput: {
        height: 40,
        width: width,
        marginBottom: 5,
        backgroundColor: 'white',
        textAlign: 'center',
		borderRadius:5
    },
	settingStyle:{
        flexDirection:'row',
        justifyContent:'space-between',
        width:width - 10,

	},
	margin:{
	  fontWeight:"bold",
	}
});
